package models

import (
	"gorm.io/gorm"
)

// 管理员账号
type Admin struct {
	gorm.Model
	Code     string //机构代码
	Account  string //账号
	Password string //密码
}

// 用户账号表
type User struct {
	gorm.Model
	Mobile   string //手机号
	Account  string //账号
	Password string //密码
	SAId     int64  //校区ID
}

// Permission int64 //权限 0-普通用户 1-管理员

func (u *User) GetUserByMobile(db *gorm.DB, mobile string) error {
	return db.Where("mobile=?", mobile).Limit(1).Find(&u).Error
}

func (u *User) Register(db *gorm.DB) error {
	return db.Create(&u).Error
}

// 校区表
type SchoolArea struct {
	gorm.Model
	Image      string
	SchoolName string //校区名称
	Types      int64  //类型
	Mobile     string //手机
	Ads        string //地址
	Status     int64  `gorm:"type:int(1);default:1;comment:'校区状态：1-正常 2-异常'"`
}

func (sa *SchoolArea) CreateSA(db *gorm.DB) error {
	return db.Create(&sa).Error
}

func (sa *SchoolArea) ListSA(db *gorm.DB, SName string, status int64,
	page, pageSize int) (list []SchoolArea, err error) {
	query := db

	if SName != "" {
		query = query.Where("school_name like ?", "%"+SName+"%")
	}
	if status != 0 {
		query = query.Where("status=?", status)
	}

	err = query.Order("created_at desc").
		Scopes(Paginate(page, pageSize)).
		Find(&list).Error

	return list, err
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 20
		case pageSize <= 0:
			pageSize = 20
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

type UserList struct {
	Mobile     string //手机号
	Account    string //账号
	SchoolName string //校区名称
}

func (ul *UserList) UserList(db *gorm.DB, mobile string) (list []UserList, err error) {
	query := db.Model(&User{})

	if mobile != "" {
		query = query.Where("users.mobile =?", mobile)
	}

	err = query.
		Select("users.mobile as mobile,users.account as account," +
			"school_areas.school_name as school_name").
		Joins("JOIN school_areas ON users.sa_id=school_areas.id").
		Find(&list).Error

	return
}
